<template>
  <div>
    <el-dialog :title="flag.isAdd?'角色添加':'角色修改'" :visible.sync="flag.isShow" @closed="closed">
      <el-form :model="form">
        <el-form-item label="角色名称" label-width="70px">
          <el-input v-model="form.rolename" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色权限" label-width="70px">
          <el-tree
            :data="reqMenuListData"
            :props="{children: 'children',label: 'title'}"
            show-checkbox
            node-key="id"
            ref="tree"
          ></el-tree>
        </el-form-item>
        <el-form-item label="状态" label-width="70px">
          <el-switch
            v-model="form.status"
            active-color="#13ce66"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="flag.isShow = false">取 消</el-button>
        <el-button type="primary" @click="add" v-if="flag.isAdd">添加</el-button>
        <el-button type="primary" @click="change" v-else>修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { roleAdd, roleInfo, roleEdit } from "../../../request/api";
export default {
  data() {
    return {
      form: {
        rolename: "",
        menus: "",
        status: 1
      }
    };
  },
  props: ["flag", "reqMenuListData"],
  components: {},
  methods: {
    add() {
      this.form.menus = JSON.stringify(this.$refs.tree.getCheckedKeys());
      //添加
      roleAdd(this.form);
      //消失
      this.flag.isShow = false;
      //清空
      this.clear();
      //请求数据
      this.$emit("req");
    },
    // 修改
    change() {
      //消失
      this.flag.isShow = false;
      this.form.menus = JSON.stringify(this.$refs.tree.getCheckedKeys());
      roleEdit(this.form).then(res => {
        if (res.data.code == 200) {
          //清空
          this.clear();
          //请求数据
          this.$emit("req");
        }
      });
    },
    //清空
    clear() {
      this.form.rolename = "";
      this.form.status = 1;
      this.$refs.tree.setCheckedKeys([]);
    },
    //请求一个角色
    reqInfo(id) {
      roleInfo({ id: id }).then(res => {
        this.form = res.data.list;
        this.$refs.tree.setCheckedKeys(JSON.parse(res.data.list.menus));
        this.form.id = id;
        console.log(this.form);
      });
    },
    closed() {
      if (!this.flag.isAdd) {
        this.clear();
      }
    }
  },
  mounted() {}
};
</script>
<style lang="less" scoped>
</style>